package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.ConfigurationHandle;
import com.baichang.framework.utils.DateUtil;
import com.baichang.framework.utils.LogUtils;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.*;
import com.baichang.taoshunda.entity.em.CompanyBalanceState;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.ExportExcelUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CashServiceImpl implements CashService {

    @Autowired
    private CashDao cashDao;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private UserBankService userBankService;

    @Autowired
    private BankcardTypeDao bankcardTypeDao;

    @Autowired
    private DeliveryClerkService deliveryClerkService;

    @Autowired
    private DeliveryblancceDao deliveryblancceDao;

    @Autowired
    private CompanyBalanceService companyBalanceService;

    @Autowired
    private BussinessDao bussinessDao;

    @Autowired
    private DeliveryClerkDao deliveryClerkDao;

    /**
     * 根据商家编号获取商家提现记录
     *
     * @param bussinessId 商家编号
     * @return
     */
    @Override
    public List<Map<String, Object>> findCashHistoryByBussinessId(Integer bussinessId) {
        return cashDao.findCashHistoryByBussinessId(bussinessId);
    }

    /**
     * 查看商家提现列表
     *
     * @param bussId 商家编号
     * @return
     */
    @Override
    public List<Map<String, Object>> findCashList(Integer bussId) {
        return cashDao.findCashList(bussId);
    }

    /**
     * 商家提现
     *
     * @param bussId     商家编号
     * @param bankCardId 银行卡编号
     * @param money      提现金额
     * @return
     */
    @Override
    public boolean cash(Integer bussId, Integer bankCardId, Double money) throws ServiceException {
        Bussiness bussiness = businessService.getBusinessById(bussId);
        if (bussiness.getState() == 0) {
            throw new ServiceException("商家已被禁用不能进行提现，如有问题请联系客服！");
        }
        if (bussiness.getBalance().compareTo(BigDecimal.valueOf(money)) == -1) {
            throw new ServiceException("您的余额不足");
        }
        int count = cashDao.getCountByCompanyId(bussId);
        if (count >= 3) {
            throw new ServiceException("今日提现次数已达上限！");
        }
        String dateStr = DateUtil.formatDate(new Date(), DateUtil.DATE_FORMAT);
        //修改商家余额
        businessService.updateBussinessBalance(bussId, money, CompanyBalanceState.提现.getCode(), dateStr + " 提现", 0);
        UserBank userBank = userBankService.getUserBankBeanById(bankCardId);        //银行卡信息不存在修改，问题是传值错误
//        companyBalanceService.saveCash(bussiness,money);
        Cash cash = new Cash();
        cash.setBankCard(userBank.getCardNumber());
        cash.setBankcardId(bankCardId);
        BankcardType bankcardType = bankcardTypeDao.getEntityById(userBank.getCardTypeId());
        if (bankcardType == null) {
            throw new ServiceException("银行不存在");
        }

        cash.setBankName(bankcardType.getCardName());
        cash.setCompanyId(bussId);
        cash.setType(1);
        cash.setCreated(new Date());
        cash.setMobile(bussiness.getBussTel());
        cash.setMoney(BigDecimal.valueOf(money));
        cash.setName(userBank.getUserName());
        cash.setState(1);
        return cashDao.save(cash) > 0;
    }


    /**
     * 商家提现列表  busscashQuery
     */
    @Override
    public Page<Map<String, Object>> busscashQuery(int nowPage, int pageSize, String bussName, String startTime, String endTime, int cashstatus, int companyId) throws ServiceException {
        return cashDao.busscashQuery(nowPage, pageSize, bussName, startTime, endTime, cashstatus, companyId);
    }


    /**
     * 商家提现列表的导出  busscashQueryExport busscashQueryExport(bussName,startTime,endTime,cashstatus);
     *
     * @param ids
     * @param response
     */

    @Override
    public String busscashQueryExport(HttpServletResponse response, String ids) throws ServiceException {

        ConfigurationHandle configurationHandle = new ConfigurationHandle("excel.properties");
        String downUrl = configurationHandle.getStringValue("downloadUrl");
        List<Map<String, Object>> list = cashDao.busscashQueryExport(ids);
        for (Map<String, Object> pro : list) {
            pro.put("attachment", downUrl + pro.get("attachmentPath"));

        }

        String[] heads = {"提现编号#id", "商家编号#companyId", "商家名称#name",
                "提现金额#money", "提现时间#created", "状态#state", "银行卡号#bankCard", "持卡人姓名#name", "提现银行#bankName", "手机号#mobile", "拒绝理由#reason",
                "处理时间#dealTime", "银行卡编号#bankcardId"};
        try {
            return ExportExcelUtils.export(response, "商家提现记录", heads, list);
        } catch (Exception e) {
            LogUtils.getInstance().error("导出商家提现记录时出错");
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 提现审核通过与审核失败
     */
    @Override
    public boolean audit(int id, int state, String auditPersonName, String auditReason, Integer companyId, BigDecimal money, Integer deliveryId) throws ServiceException {
        if (state == 3) {
            if (companyId == 0) {
                DeliveryClerk deliveryClerk = deliveryClerkDao.getEntityById(deliveryId);
                Double deliveryMoney = money.add(deliveryClerk.getBalance()).doubleValue();
                deliveryClerkDao.updateBalance(deliveryId, deliveryMoney);
            } else {
                Bussiness map = bussinessDao.getEntityById(companyId);
                Double allMoney = money.add(map.getBalance()).doubleValue();
                bussinessDao.updateBussinessBalance(companyId, allMoney);
            }
        }
        return cashDao.audit(id, state, auditPersonName, auditReason);
    }

    /**
     * 配送员提现列表  busscashQuery
     */
    @Override
    public Page<Map<String, Object>> delivercashQuery(int nowPage, int pageSize, String bussName, String startTime, String endTime, int cashstatus, int companyId) throws ServiceException {
        return cashDao.delivercashQuery(nowPage, pageSize, bussName, startTime, endTime, cashstatus, companyId);
    }

    /**
     * 配送员提现列表的导出
     *
     * @param ids
     * @param response
     */
    @Override
    public String delivercashQueryExport(HttpServletResponse response, String ids) throws ServiceException {
        ConfigurationHandle configurationHandle = new ConfigurationHandle("excel.properties");
        String downUrl = configurationHandle.getStringValue("downloadUrl");
        List<Map<String, Object>> list = cashDao.delivercashQueryExport(ids);
        for (Map<String, Object> pro : list) {
            pro.put("attachment", downUrl + pro.get("attachmentPath"));
        }

        String[] heads = {"提现编号#id", "配送员编号#deliveryId", "配送员姓名#name",
                "提现金额#money", "提现时间#created", "状态#state", "银行卡号#bankCard", "提现银行#bankName", "手机号#mobile", "拒绝理由#reason",
                "处理时间#dealTime", "银行卡编号#bankcardId"};
        try {
            return ExportExcelUtils.export(response, "商家提现记录", heads, list);
        } catch (Exception e) {
            LogUtils.getInstance().error("导出配送员提现记录时出错");
            e.printStackTrace();
        }

        return "";
    }


    /**
     * 提现列表的查询  indexQuery
     */

    @Override
    public Page<Map<String, Object>> indexQuery(int nowPage, int pageSize, String bussName, int cashstatus, String startTime, String endTime, String checkBusinessName, String checkDeliveryName) throws ServiceException {
        return cashDao.indexQuery(nowPage, pageSize, bussName, cashstatus, startTime, endTime, checkBusinessName, checkDeliveryName);
    }

    /**
     * 查看配送员的提现记录
     *
     * @param disId
     * @return
     */
    @Override
    public List<Map<String, Object>> findCashHistoryByDisId(Integer disId) {
        return cashDao.findCashHistoryByDisId(disId);
    }

    /**
     * 提现列表
     *
     * @param disId    配送员编号
     * @param nowPage  当前页
     * @param pageSize @return
     */
    @Override
    public List<Map<String, Object>> findDeliveryCashList(Integer disId, Integer nowPage, int pageSize) {
        return cashDao.findDeliveryCashList(disId, nowPage, pageSize);
    }

    /**
     * 提现
     *
     * @param disId      配送员
     * @param bankCardId 银行卡编号
     * @param money      钱数
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean cashByDelivery(Integer disId, Integer bankCardId, Double money) throws ServiceException {
        DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
        if (deliveryClerk.getDisState() != 1) {
            throw new ServiceException("您已被禁用不能进行提现！");
        }
        if (deliveryClerk.getBalance().compareTo(BigDecimal.valueOf(money)) == -1) {
            throw new ServiceException("您的余额不足");
        }
        UserBank userBank = userBankService.getUserBankBeanById(bankCardId);
        Cash cash = new Cash();
        cash.setBankCard(userBank.getCardNumber());
        cash.setBankcardId(bankCardId);
        BankcardType bankcardType = bankcardTypeDao.getEntityById(userBank.getCardTypeId());
        if (bankcardType == null) {
            throw new ServiceException("银行不存在");
        }
        cash.setBankName(bankcardType.getCardName());
        cash.setDeliveryId(disId);
        cash.setCreated(new Date());
        cash.setType(1);
        cash.setMobile(deliveryClerk.getAccount());
        cash.setMoney(BigDecimal.valueOf(money));
        cash.setName(userBank.getUserName());
        cash.setState(1);
        if (cashDao.save(cash) > 0) {
            deliveryClerk.setBalance(deliveryClerk.getBalance().subtract(BigDecimal.valueOf(money)));
            deliveryblancceDao.updateMoney(deliveryClerk);
            DeliveryBalance deliveryBalance = new DeliveryBalance();
            deliveryBalance.setBalance(BigDecimal.valueOf(money));
            deliveryBalance.setBalanceState("-");
            deliveryBalance.setCreated(new Date());
            deliveryBalance.setDeliveryId(disId);
            deliveryBalance.setSourceType(2);
            deliveryBalance.setCurrentAmount(deliveryClerk.getBalance().subtract(BigDecimal.valueOf(money)));
            return deliveryblancceDao.save(deliveryBalance) > 0;
        }
        return cashDao.save(cash) > 0;
    }

    @Override
    public Map<String, Object> blanceList(Integer disId, String startTime, String endTime, Integer nowPage, int pageSize) throws ServiceException {
        Map<String, Object> map = new HashedMap();
        DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
        if (deliveryClerk == null) {
            throw new ServiceException("无此配送员");
        }
        map.put("allmoney", deliveryblancceDao.getTodayMoney(disId, startTime, endTime).get("toDayMoney"));
        map.put("list", deliveryblancceDao.blanceList(disId, startTime, endTime, nowPage, pageSize));
        return map;
    }
}
